package com.item.action;

import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.base.Page;
import com.base.dialect.PaginationSupport;
import com.base.util.DateUtil;
import com.item.dao.model.Essence;
import com.item.dao.model.EssenceAuthor;
import com.item.dao.model.EssenceAuthorExample;
import com.item.dao.model.EssenceCourse;
import com.item.dao.model.EssenceCourseExample;
import com.item.dao.model.EssenceExample;
import com.item.dao.model.Note;
import com.item.dao.model.NoteAuthor;
import com.item.dao.model.NoteAuthorExample;
import com.item.dao.model.NoteExample;
import com.item.dao.model.EssenceAuthorExample.Criteria;
import com.item.exception.JSONRepUtils;
import com.item.service.EssenceAuthorService;
import com.item.service.EssenceCourseService;
import com.item.util.SubjectUtils;

@Controller
public class EssenceAuthorController {
	@Autowired
	private EssenceAuthorService authorService;
	@Autowired
	private EssenceCourseService courseService;
	
	@RequestMapping("/listEssenceAuthor")
	@ResponseBody
	public String list(Page param,EssenceAuthor author) throws Exception{
		EssenceAuthorExample example = new EssenceAuthorExample();
		PaginationSupport.setContext(param.getPageStart(), param.getPageSize(), null);
		Criteria criteria = example.createCriteria();
		
		//以下两个字段用来做筛选  分别是title和source的模糊匹配
		
		if(StringUtils.isNotBlank(author.getName())){
			criteria.andNameLike("%" + author.getName() +"%");
		}
		if(StringUtils.isNotBlank(author.getDescription())){
			criteria.andDescriptionLike("%" + author.getDescription()+"%");
		}
		if(StringUtils.isNotBlank(author.getSlogan())){
			criteria.andSloganLike("%" + author.getSlogan()+"%");
		}
		if(author.getType() != null){
			criteria.andTypeEqualTo(author.getType());
		}
		if(author.getIsLock() != null){
			criteria.andIsLockEqualTo(author.getIsLock());
		}
		if(StringUtils.isNotBlank(author.getSubject())){
			criteria.andSubjectLike("%" + author.getSubject()+"%");
		}
		if(StringUtils.isNotBlank(author.getCourses())){
			criteria.andCoursesLike("%" + author.getCourses()+"%");
		}
//		if(essence.getTime() != null){
//			criteria.andTimeEqualTo(essence.getTime());
//		}
		example.setOrderByClause("type ASC,top DESC,last_update_time DESC");
		List<EssenceAuthor> list = authorService.selectByExample(example);
		return JSONRepUtils.serialize(new Page(PaginationSupport.getContext().getTotalCount(), list), 0);
	}
	
	@RequestMapping("/showlistEssenceAuthor")
	public String list() {
		return "essenceauthor/authorList";
	}
	
	@RequestMapping("/toEditEssenceAuthor")
	public String toEdit()throws Exception{
		return "essenceauthor/authorEdit";
	}
	
	@RequestMapping(value="/saveEssenceAuthor",method=RequestMethod.POST)
	@ResponseBody
	public String save(EssenceAuthor author, HttpSession session)throws Exception{
		try{
			if(StringUtils.isBlank(author.getId())){
				author.setIsLock(0);
				author.setCollectCount(new Random().nextInt(800));
				author.setCreateTime(new Date());
				author.setTop(0);
//				author.setCourses("");
				author.setLastUpdateTime(new Date());
				if(author.getType() == 2){
					author.setSubject("1,2,3");
					author.setBelong("");
					author.setBelongid("");
				}else{
					setBelong(author, author.getBelongid());
				}
				authorService.insert(author);
			}else{
				author.setModifyTime(new Date());
				if(author.getType()==1){
					setBelong(author, author.getBelongid());
				}
				authorService.updateByPrimaryKeySelective(author);
			}
		}catch(Exception e){
			e.printStackTrace();
			return "{\"success\":false}";
		}
		
		return "{\"success\":true}";
	}
	public void setBelong(EssenceAuthor author, String belongIds){
		String[] ids = belongIds.split(",");
		StringBuilder sb = new StringBuilder();
		for(String id : ids){
			sb.append(authorService.selectByPrimaryKey(id).getName()+",");
		}
		author.setBelong(sb.toString().substring(0, sb.length()-1));
	}
	
	@RequestMapping(value="/findByIdEssenceAuthor")
	@ResponseBody
	public String findById(String id,HttpSession session)throws Exception{		
		EssenceAuthor n = authorService.selectByPrimaryKey(id);
		return JSONRepUtils.serialize(n, 0);
	}
	
	@RequestMapping("/getEssenceAuthors")
	@ResponseBody
	public String getEssenceAuthors(Integer type){
		if(type == null)
			type = 2;
		EssenceAuthorExample naex = new EssenceAuthorExample();
		naex.createCriteria().andTypeEqualTo(type);
		List<EssenceAuthor> lists = authorService.selectByExample(naex);
		return JSONRepUtils.serialize(lists, 0);
	}
	
	@RequestMapping("/getEssenceCourses")
	@ResponseBody
	public String getEssenceCourses(Integer type){
		if(type == null)
			type = 1;
		EssenceCourseExample ecex = new EssenceCourseExample();
		ecex.createCriteria().andSubjectEqualTo(type.toString());
		List<EssenceCourse> lists = courseService.selectByExample(ecex);
		return JSONRepUtils.serialize(lists, 0);
	}
	
	@RequestMapping("/delEssenceAuthor")
	@ResponseBody
	public String del(String id,String url,HttpSession session)throws Exception{
//		WebPageFileController fileController = new WebPageFileController();
		String[] ids = id.split(",");
		int len = ids.length;
		for(int i = 0; i < len; i++) {
			authorService.deleteByPrimaryKey(ids[i]);
//			fileController.deleteFile(urls[i]);
		}
		return "{\"success\":true}";
	}
	
	@RequestMapping("/moveUpEssenceAuthor")
	@ResponseBody
	public String moveUp(String id,HttpSession session) throws Exception {
		return processMove(id, 0);
	}
	
	@RequestMapping("/moveDownEssenceAuthor")
	@ResponseBody
	public String moveDown(String id,HttpSession session) throws Exception {
		return processMove(id, 1);
	}
	
	/**
	 * 操作上移下移的动作
	 * @param uid
	 * @param type
	 * @return
	 */
	public String processMove(String uid,int type){
		
		EssenceAuthor now = authorService.selectByPrimaryKey(uid);
		if(now == null){
			return "{\"success\":false}";
		}
		EssenceAuthorExample sdex = new EssenceAuthorExample();
		if(type == 0){
			sdex.createCriteria().andSubjectEqualTo(now.getSubject()).andTopGreaterThan(now.getTop());
			sdex.setOrderByClause("top ASC");
		}else{
			sdex.createCriteria().andSubjectEqualTo(now.getSubject()).andTopLessThan(now.getTop());
			sdex.setOrderByClause("top DESC");
		}
		PaginationSupport.setContext(1, 1, null);
		List<EssenceAuthor> nexts = authorService.selectByExample(sdex);
		if(nexts == null || nexts.size() == 0){
			return "{\"success\":false}";
		}
		EssenceAuthor next = nexts.get(0);
		Integer top = next.getTop();
		next.setTop(now.getTop());
		authorService.updateByPrimaryKeySelective(next);
		now.setTop(top);
		authorService.updateByPrimaryKeySelective(now);
		return "{\"success\":true}";
	}
	
	@RequestMapping("/showOrHideAuthor")
	@ResponseBody
	public String showOrHide(String id,Integer type){
		System.out.println(id+type);
		EssenceAuthor now = authorService.selectByPrimaryKey(id);
		if(now != null){
			now.setIsLock(type);
			authorService.updateByPrimaryKeySelective(now);
		}
		return "{\"success\":true}";
	}
	
	
}

